/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sdd.facades.persistence;

import com.sdd.entities.Customer;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 *
 * @author ceu
 */
@Stateless
public class CustomerPersistenceFacade extends AbstractPersistenceFacade<Customer> {

    @PersistenceContext(unitName = "SDDStore-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public Customer getCustomerbyLogin(String login) {
        return getCustomer("login", login);
    }

    public Customer getCustomerbyEmail(String email) {
        return getCustomer("email", email);
    }

    public boolean existLogin(String login) {
        if (getCustomerbyLogin(login) == null) {
            return false;
        }
        return true;
    }

    public boolean existEmail(String email) {
        if (getCustomerbyEmail(email) != null) {
            return true;
        }
        return false;
    }

    private Customer getCustomer(String field, String parameter) {

        CriteriaQuery<Customer> cq = em.getCriteriaBuilder().createQuery(Customer.class);
        Root<Customer> customer = cq.from(Customer.class);
        cq.where(em.getCriteriaBuilder().equal(customer.get(field), parameter));
        List<Customer> resultList = em.createQuery(cq).getResultList();
        if (resultList != null && resultList.size() > 0) {
            return resultList.get(0);
        } else {
            return null;
        }
    }

    public CustomerPersistenceFacade() {
        super(Customer.class);
    }
}
